<template>
  <div class="page-content">
    <!-- 表格顶部区域 -->
    <TableBar
      :columns="showColumns"
      @changeColumn="
        (newcolumns) => {
          this.columns = newcolumns;
        }
      "
      :layout="layout"
    >
      <div slot="bottom">
        <el-row>
          <el-col :span="6">
            <el-button
              type="primary"
              plain
              size="mini"
              @click="dialog"
              v-if="!hiddenBtn"
              v-auth="'processing_product_insert'"
              >新增</el-button
            >
          </el-col>
          <el-col :span="12">
            <el-select
              v-model="processId"
              placeholder="请选择加工厂"
              size="mini"
              v-auth="'processing_product_insert'"
            >
              <el-option
                v-for="item in processList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </el-col>
        </el-row>
      </div>
      <div slot="top">
        <el-form label-width="55px">
          <el-row :gutter="20">
            <el-col :xs="24" :sm="12" :lg="6">
              <el-form-item label="名称：">
                <el-input placeholder="名称"></el-input>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :lg="6">
              <el-form-item label="地址：">
                <el-input placeholder="地址"></el-input>
              </el-form-item>
            </el-col>

            <el-row
              :xs="24"
              :sm="12"
              :lg="6"
              style="float: right; margin-right: 10px"
            >
              <el-button type="primary" v-auth="'processing_product_select'">搜索</el-button>
              <el-button v-auth="'processing_product_select'">重置</el-button>
            </el-row>
          </el-row>
        </el-form>
      </div>
    </TableBar>

    <!-- 表格区域 -->
    <TheTable
      :data="allList"
      :page.sync="page"
      :showPage="showPage"
      @changeSize="
        (size) => {
          this.page.pageSize = size.pageSize;
          this.setAllList();
        }
      "
      @changePage="
        (page) => {
          this.page.current = page.current;
          this.setAllList();
        }
      "
      :Bottom="35"
    >
      <div class="item" effect="dark" placement="top-start">
        <el-table-column type="expand" fixed="left">
          <template slot-scope="scope">
            <el-form label-position="left" class="demo-table-expand">
              <ShowRow
                :columns="showColumns"
                :row="scope.row"
                num="3"
              ></ShowRow>
            </el-form>
            <h4>产品视频信息</h4>
            <hr />
            <div v-if="scope.row.video" style="margin-bottom: 20px">
              <el-table
                :data="JSON.parse(scope.row.video)"
                stripe
                style="width: 100%"
              >
                <el-table-column prop="id" label="视频序号" align="center">
                </el-table-column>
                <el-table-column prop="name" label="视频名称" align="center">
                </el-table-column>
                <el-table-column label="视频网址" align="center"
                  ><template slot-scope="scope"
                    ><el-link
                      type="primary"
                      :href="scope.row.url"
                      target="_blank"
                      >{{ scope.row.url }}</el-link
                    ></template
                  ></el-table-column
                >
              </el-table>
            </div>

            <h4>产品购买渠道</h4>
            <hr />
            <div v-if="scope.row.purchaseChannel">
              <el-table
                :data="JSON.parse(scope.row.purchaseChannel)"
                stripe
                style="width: 100%"
              >
                <el-table-column prop="id" label="渠道序号" align="center">
                </el-table-column>
                <el-table-column prop="name" label="渠道名称" align="center">
                </el-table-column
                ><el-table-column
                  prop="platform"
                  label="电商平台"
                  align="center"
                >
                </el-table-column>
                <el-table-column label="渠道网址"
                  ><template slot-scope="scope"
                    ><el-link
                      type="primary"
                      :href="scope.row.url"
                      target="_blank"
                      >{{ scope.row.url }}</el-link
                    ></template
                  ></el-table-column
                >
              </el-table>
            </div>
          </template>
        </el-table-column>
      </div>

      <div
        v-for="item in showColumns"
        :key="item.id"
        class="item"
        effect="dark"
        placement="top-start"
      >
        <el-table-column
          :label="item.name"
          v-if="item.show"
          :prop="item.prop"
          show-overflow-tooltip
        ></el-table-column>
      </div>

      <el-table-column
        label="电子价签状态"
        prop="tagStatus"
        show-overflow-tooltip
      >
        <template slot-scope="scope">
          <el-tag size="medium" type="success" v-if="scope.row.tagStatus == 1"
            >启用</el-tag
          >
          <el-tag size="medium" type="danger" v-else>禁用</el-tag>
        </template>
      </el-table-column>

      <el-table-column label="产品等级" prop="level" show-overflow-tooltip>
        <template slot-scope="scope">
          <el-tag size="medium" type="success" v-if="scope.row.level == 1"
            >一等品</el-tag
          >
          <el-tag size="medium" type="info" v-else-if="scope.row.level == 2"
            >二等品</el-tag
          >
          <el-tag size="medium" type="warning" v-else>三等品</el-tag>
        </template>
      </el-table-column>

      <el-table-column label="操作" align="center">
        <template slot-scope="scope">
          <el-button
            mini
            type="primary"
            icon="el-icon-edit"
            size="mini"
            @click="dialog(scope.row)"
            v-auth="'processing_product_update'"
          ></el-button>
          <el-button
            mini
            type="danger"
            icon="el-icon-delete"
            size="mini"
            @click="delInfo(scope.row.id)"
            v-auth="'processing_product_delete'"
          ></el-button>
        </template>
      </el-table-column>
    </TheTable>

    <!-- 表单框 -->
    <el-dialog
      :title="dialogTitle"
      width="50%"
      :visible.sync="showDialog"
      top="20vh"
      @close="
        () => {
          this.showDialog = false;
          this.from = {};
        }
      "
    >
      <el-form
        label-position="right"
        ref="formRef"
        :rules="rules"
        :model="form"
        label-width="135px"
      >
        <FormRow :form="form" :label-prop="formColumns" num="2"></FormRow>
        <el-form-item size="large" class="dialog-bottom-btn">
          <el-button type="primary" @click="submit">确定</el-button>
          <el-button @click="showDialog = false" v-auth="'processing_product_insert'">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import { mapState } from "vuex";
import ShowRow from "../../components/OrderManagement/ShowRow";
import FormRow from "../../components/ProcessingPlantManagement/public/FormRow";
import {
  getAllInfoByPage,
  getAllInfoById,
  getInfoById,
  addInfo,
  delInfoById,
  editInfo,
} from "../../Api/processingplant/process_product_infomation";
export default {
  name: "ProcessingProduct",
  components: { ShowRow, FormRow },
  data() {
    return {
      allList: [],
      columns: [
        // 表头数据
        { name: "产品编号", show: true, prop: "id" },
        { name: "产品名称", show: true, prop: "name" }, // input
        {
          name: "保质期",
          show: false,
          prop: "expirationDate",
        }, // InputNumber
        { name: "品牌", show: false, prop: "brand" }, // input
        {
          name: "最佳食用期/天",
          show: false,
          prop: "bestBeforeDate",
          inputNumber: {
            min: 0,
          },
        }, // InputNumber
        { name: "所属加工厂id", show: false, prop: "factoryId" },
        {
          name: "产品等级",
          show: true,
          prop: "level",
          select: {
            options: [
              { label: "一等品", value: 1 },
              { label: "二等品", value: 2 },
              { label: "三等品", value: 3 },
            ],
          },
        }, // Select
        {
          name: "单价/元",
          show: false,
          prop: "price",
          inputNumber: {
            min: 0,
          },
        }, // InputNumber
        { name: "产品二维码", show: false, prop: "qrCode" }, // 二维码
        { name: "产品sku", show: false, prop: "sku" }, // input
        {
          name: "规格",
          show: false,
          prop: "specification",
        },
        {
          name: "电子价签状态",
          show: true,
          prop: "tagStatus",
          select: {
            options: [
              { label: "禁用", value: 0 },
              { label: "启用", value: 1 },
            ],
          },
        }, // Select
        {
          name: "产品类型",
          show: false,
          prop: "type",
          select: {
            options: [{ label: "散货", value: "散货" }],
          },
        }, // Select
        { name: "单位", show: false, prop: "unit" }, // input
        {
          name: "所属种类",
          show: false,
          prop: "variety",
          select: {
            options: [{ label: "肉鸽", value: "肉鸽" }],
          },
        }, // input
        {
          name: "产品视频信息",
          show: false,
          prop: "video",
        }, // 视频
        {
          name: "产品购买渠道",
          show: false,
          prop: "purchaseChannel",
        }, // input
        {
          name: "产品简介",
          show: false,
          prop: "introduction",
          textarea: "textarea",
        }, // 副文本, 先用多行文本代替
      ],
      layout: "search, refresh, column",
      form: {}, // 存放表单数据
      showDialog: false, // 控制表单的显示与隐藏
      showPage: true, // 显示分页
      hiddenBtn: false, // 用于控制添加按钮的显示于隐藏，
      page: {
        current: 1,
        pageSize: 10,
        total: 0,
      },
      dialogTitle: "新增",
      videoLable: [
        "视频信息",
        { name: "视频名称", prop: "name" },
        { name: "视频网址", prop: "url" },
      ],
      channelLable: [
        "渠道信息",
        { name: "渠道名称", prop: "name" },
        { name: "渠道平台", prop: "platform" },
        { name: "渠道网址", prop: "url" },
      ],
      processId: "", // 加工厂编号
    };
  },
  computed: {
    // 用于列表展示
    showColumns() {
      let noArr = ["level", "tagStatus", "video", "purchaseChannel"];
      return this.columns.filter((item) => {
        return !noArr.includes(item.prop);
      });
    },

    // 用于表单填写
    formColumns() {
      let noArr = [
        "id",
        "video",
        "purchaseChannel", // 渠道
        "factoryId", // 加工厂id
      ];
      return this.columns.filter((item) => {
        return !noArr.includes(item.prop);
      });
    },

    // 校验规则
    rules() {
      let ruleList = {};
      this.formColumns.forEach((item) => {
        ruleList[item.prop] = [
          { required: true, message: `请填写${item.name}`, trigger: "blur" },
        ];
      });
      return ruleList;
    },

    ...mapState("process", {
      processList: (state) => state.processList,
    }),
  },
  watch: {
    // 监听加工厂变化
    processId(processId) {
      this.setAllList();
    },
  },
  created() {
    this.processId = this.processList[0].id; // 默认是第一个加工厂
    // 如果没有加工厂，隐藏新增按钮
    if (this.processList.length !== 0) {
      this.processId = this.processList[0].id;
    } else {
      this.hiddenBtn = true;
    }
  },
  methods: {
    // 获取数据
    async setAllList() {
      const { data: res } = await getAllInfoByPage(
        this.processId,
        this.page.current,
        this.page.pageSize
      );
      if (res.statusCode !== 20000) {
        this.$message.error(res.message);
      }
      this.allList = res.data.records;
      this.page.total = res.data.total;
    },

    // 打开弹窗
    dialog(row = undefined) {
      let form = JSON.parse(JSON.stringify(row));
      if (row.id) {
        // 修改
        this.form = form;
        this.dialogTitle = "修改";
      } else {
        // 增加
        this.dialogTitle = "新增";
        this.form.factoryId = this.processId;
      }
      this.showDialog = true;
    },

    // 提交按钮
    async submit() {
      this.$refs.formRef.validate(async (access, obj) => {addInfo
        console.log(this.form);
        if (access) {
          if (!this.form.id) {
            // 增加
            const { data: res } = await addInfo(this.form);
            if (res.statusCode !== 20000) {
              console.error(res.message);
              this.$message.error(res.message);
            } else {
              this.clearform();
              this.$message.success(res.message);
              this.setAllList();
            }
          } else {
            // 修改
            const { data: res } = await editInfo(this.form);
            if (res.statusCode !== 20000) {
              console.error(res.message);
              this.$message.error(res.message);
            } else {
              this.clearform();
              this.$message.success(res.message);
              this.setAllList();
            }
          }
        }
      });
      this.$refs.formRef.validate(async (val) => {
        if (!val) return false;
        if (!this.form.id) {
          // 增加
          const { data: res } = await addInfo(this.form);
          if (res.statusCode !== 20000) {
            console.error(res.message);
            this.$message.error(res.message);
          } else {
            this.clearform();
            this.$message.success(res.message);
            this.setAllList();
          }
        } else {
          // 修改
          const { data: res } = await editInfo(this.form);
          if (res.statusCode !== 20000) {
            console.error(res.message);
            this.$message.error(res.message);
          } else {
            this.clearform();
            this.$message.success(res.message);
            this.setAllList();
          }
        }
      });
    },

    // 删除按钮
    async delInfo(id) {
      this.$confirm("此操作将永久删除该信息，请谨慎操作, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const { data: res } = await delInfoById(id);
          console.log("res: ", res);
          if (res.statusCode !== 20000) {
            this.$message.error(res.message);
          } else {
            this.setAllList();
            this.$message.success(res.message);
          }
        })
        .catch(() => {
          return this.$message.info("已取消删除！");
        });
    },
  },
};
</script>

<style lang="scss" scoped>
.el-form .el-form-item .el-input {
  width: 300px;
}
</style>